package com.health.ts.service.task;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 定时任务服务
 *
 */
@Component
@Slf4j
public class TaskService {
	
	/**
	 * redisson分布式锁
	 */
    @Autowired
    private RedissonClient redissonClient;
    
	@Async // 异步执行，线程之间不会互相干扰
//	@PostConstruct // 加上该注解项目启动时就执行一次该方法
	@Scheduled(cron = "${ts.task.cron}") // cron表达式
	public void teskTask1() {
		log.info("定时任务teskTask1开始执行");
		RLock lock = redissonClient.getLock("testTask");
		boolean getLock = false;
		try {
			if (getLock = lock.tryLock(0, 50, TimeUnit.SECONDS)) {
				log.info("Redisson获取到分布式锁，ThreadName:{}", Thread.currentThread().getName());
				// 执行业务
				TimeUnit.SECONDS.sleep(20);
			} else {
				log.info("Redisson没有获取到分布式锁，ThreadName:{}", Thread.currentThread().getName());
			}
		} catch (InterruptedException e) {
			log.error("Redisson分布式锁获取异常", e);
		} finally {
			if (!getLock) {
				return;
			}
			lock.unlock();
			log.info("Redisson分布式锁释放锁");
		}
		log.info("定时任务teskTask1执行结束");
	}
}
